package controller

import (
	"biliPushServer/global/response"
	"biliPushServer/server"
	"biliPushServer/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"io"
	"io/ioutil"
	"net/http"
	"os"
)

type Upload struct {
	server *server.Upload
}

func (cli *Upload) Router(URL string, Router *gin.RouterGroup) {
	cli.server = new(server.Upload)
	router := Router.Group(URL)
	router.POST("", cli.ProgramPost)
	router.GET("", cli.ProgramGet)
}

// ProgramPost 上传文件
func (cli *Upload) ProgramPost(c *gin.Context) {
	 file, fileHeader, err := c.Request.FormFile("program")
	if err != nil {
		response.FailWithMessage("Bad request", c)
		return
	}
	fileName := fileHeader.Filename
	dir, _ := os.Getwd()
	dir = fmt.Sprintf("%v/upload", dir)
	if !utils.PathExists(dir) {
		err = utils.CreateDir(dir)
		if err != nil {
			response.FailWithMessage(err.Error(), c)
			return
		}
	}
	path := fmt.Sprintf("%v/%v", dir, fileName)
	if utils.PathExists(path) {
		_ = os.Remove(path)
	}
	out, _ := os.Create(path)
	defer func(out *os.File) {
		_ = out.Close()
	}(out)
	_, _ = io.Copy(out, file)
	fileMd5 := cli.server.SetHash(path, fileName)
	response.OkWithData(map[string]string{"md5": fileMd5}, c)
	return
}

// ProgramGet 下载文件
func (cli *Upload) ProgramGet(c *gin.Context) {
	fileName := c.Query("file_name")
	dir, _ := os.Getwd()
	path := fmt.Sprintf("%v/upload/%v", dir, fileName)
	c.Header("content-disposition", `attachment; filename=biliClient`)
	c.Header("Content-Disposition", "attachment; filename=hello.txt")
	c.Header("Content-Type", "application/octet-stream")
	file, err := os.Open(path)
	if err != nil {
		response.FailWithMessage("文件不存在", c)
		return
	}
	bytes, _ := ioutil.ReadAll(file)
	c.Writer.WriteHeader(http.StatusOK)
	c.Header("Accept-Length", fmt.Sprintf("%d", len(bytes)))
	_, _ = c.Writer.Write(bytes)
	return
}
